<?php 



function getUnreadMessages()
{
	$charname = $_SESSION['char'];
	$q = mysql_query("SELECT id FROM messages WHERE receiver_name = '$charname' AND status='0'")or die(alert(mysql_error()));
	return mysql_num_rows($q);
}

function deleteMessage($id)
{
	if(mysql_query("DELETE FROM messages WHERE id='$id'"))
	{
		alert("Message Deleted!");
		redirect("?page=messages");
	}
}

function newMessage($receiver = null, $subject = null, $message = null, $error = null, $id = null)
{
		if(isset($id))
		{
			$q = mysql_query("SELECT * FROM messages WHERE id='$id'");
			$f = mysql_fetch_array($q);
			$receiver = $f['sender_name'];

			if(strpos($f['subject'],'RE: RE: RE:') === false)
			{
				$subject = 'RE: '.$f['subject'];
			}
			else
			{
				$subject = $f['subject'];
			}
			
			$message = '<blockquote>'.$f['message'].'
			<h3 style=\'color:#aaa;font-style:italic;\'><span style=\'font-size:9px;\'>Original by: '.$f['sender_name'].'</span><br></h3></blockquote>
			<p>&nbsp;</p>';
		}

		echo '<table>
			<form method="POST" action="?page=messages&new&send">
				<tr><td colspan="3"><font color="red">'.$error.'</font></td></tr>
				<tr><td width="150">Receiver name:</td><td><input class="sexy" type="text" value="'.$receiver.'" name="receiver" placeholder="TinkyWinky"></td>

				<td><input type="submit" value="send" class="bsexy"></td></tr>

				<tr><td width="150">Subject:</td><td><input class="sexy" type="text" value="'.$subject.'" name="subject" placeholder="Subject"></td></tr>
				<tr><td>&nbsp;</td></tr>
				<tr><td colspan="3"><center>Message:</center></td></tr>
				<tr><td colspan="3"><textarea name="message" placeholder="Your Message">'.$message.'</textarea></td></tr>
			</form>
		</table>';
		echo "<script type='text/javascript'>CKEDITOR.replace('message');</script>";

}

function sendMessage($receiver, $subject, $message)
{
		$date = date("Y-m-d H:i:s");
		if(empty($receiver) || empty($subject) || empty($message))
		{
			$error = '- Fill in all the fields.';
		}

		$q = mysql_query("SELECT id FROM characters WHERE name='$receiver'");
		if(mysql_num_rows($q) == 0)
		{
			$error = '- This receiver doesn\'t exist or you typed the name wrong.';
		}

		if(isset($error))
		{
			newMessage($_POST['receiver'], $_POST['subject'], $_POST['message'], $error);
		}
		else
		{
			$sender = $_SESSION['char'];
			if(mysql_query("INSERT INTO messages (receiver_name, sender_name, message, subject, senddate) VALUES ('$receiver', '$sender', '$message', '$subject', '$date')")or die(alert(mysql_error())))
			{
				alert("Message has been send!");
				redirect("?page=messages");
			}
		}
}


function sendServerMessage($receiver, $subject, $message)
{
		$date = date("Y-m-d H:i:s");
		$sender = 'Server';
		mysql_query("INSERT INTO messages (receiver_name, sender_name, message, subject, senddate) VALUES ('$receiver', '$sender', '$message', '$subject', '$date')")or die(alert(mysql_error()));
}

function getMessages()
{
	if(!isset($_GET['id']) && !isset($_GET['delete']) && !isset($_GET['new']))
	{
		$i=1;

		echo '<table>';
		echo '<tr>
				<td width=40"><b>#</b></td>
				<td width="250"><b>Subject</b></td>
				<td width="100"><b>Sender</b></td>
				<td width="160"><b>Time</b></td>
			</tr>';

		$q = mysql_query("SELECT * FROM messages WHERE receiver_name = '".$_SESSION['char']."' ORDER BY senddate DESC");
		if(mysql_num_rows($q) == 0)
		{
			echo '<tr><td colspan="5">- You have 0 messages</td></tr>';
		}
		else
		{
			while($f = mysql_fetch_array($q)) 
		 	{	
		 		$class = '';
		 		if($f['status'] == 0)
		 		{
		 			$class='bold';
		 		}
					echo '<tr class="'.$class.'">
							<td width="40"><a href="?page=messages&id='.$f['id'].'">'.$i.'</a></td>
							<td width="250"><a href="?page=messages&id='.$f['id'].'">'.$f['subject'].'</a></td>
							<td width="100"><a href="?page=profile&id='.getCidFromName($f['sender_name']).'">'.$f['sender_name'].'</a></td>
							<td width="160"><a href="?page=messages&id='.$f['id'].'">'.$f['senddate'].'</a></td>
							<td><a href="?page=messages&new&reply='.$f['id'].'"><button class="bsexy">reply</button></a></td>
							<td><a href="?page=messages&delete='.$f['id'].'"><button class="bsexy">delete</button></a></td>
						  </tr>
						  ';
					
					$i++;
			}
		}
		echo'</table>';
	}
	else if(!isset($_GET['new']) && !isset($_GET['delete']) && isset($_GET['id']))
	{
		readMessage($_GET['id'], $_GET['type']);
	}
	else if(isset($_GET['new']) && !isset($_GET['delete']) && !isset($_GET['id']))
	{
		if(isset($_GET['new']) && isset($_GET['reply']))
		{
			newMessage(null, null, null, null, $_GET['reply']);	
		}
		else if(isset($_GET['receiver']))
		{
			newMessage($_GET['receiver']);
		}
		else if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_GET['send']) && $_GET['page'] == 'messages')
		{
			sendMessage($_POST['receiver'], $_POST['subject'], $_POST['message']);
		}
		else
		{
			newMessage();
		}
		
	}
	else if(!isset($_GET['new']) && isset($_GET['delete']) && !isset($_GET['id']))
	{
		$id = $_GET['delete'];
		deleteMessage($id);
	}
	
}		

function getSentMessages()
{
		$i=1;

		echo '<table>';
		echo '<tr>
				<td width=40"><b>#</b></td>
				<td width="150"><b>Subject</b></td>
				<td width="150"><b>Receiver</b></td>
				<td width="150"><b>Time</b></td>
			</tr>';

		$q = mysql_query("SELECT * FROM messages WHERE sender_name = '".$_SESSION['char']."' ORDER BY senddate DESC");
		if(mysql_num_rows($q) == 0)
		{
			echo '<tr><td colspan="5">- You have 0 Sent messages</td></tr>';
		}
		else
		{
			while($f = mysql_fetch_array($q)) 
		 	{	
		 		$class = '';
		 		if($f['status'] == 0)
		 		{
		 			$class='';
		 		}
					echo '<tr class="'.$class.'">
							<td width="40"><a href="?page=messages&type=1&id='.$f['id'].'">'.$i.'</a></td>
							<td width="150"><a href="?page=messages&type=1&id='.$f['id'].'">'.$f['subject'].'</a></td>
							<td width="150"><a href="?page=profile&id='.getCidFromName($f['receiver_name']).'">'.$f['receiver_name'].'</a></td>
							<td width="200"><a href="?page=messages&type=1&id='.$f['id'].'">'.$f['senddate'].'</a></td>
						  </tr>
						  ';
					
					$i++;
			}
		}
		echo'</table>';
}	


function readMessage($id, $type=0)
{
	$q = mysql_query("SELECT * FROM messages WHERE id='$id'");
	$f = mysql_fetch_array($q);

	if($f['status'] == 0)
	{
		mysql_query("UPDATE messages SET status='1' WHERE id='$id'");
	}

	$f['message'] = str_replace('\"', '', $f['message']);
	$f['message'] = str_replace('alt=', '', $f['message']);
	

	echo '<table>';

	echo '<tr><td width="120"><b>Sender name:</b></td><td width="180">'.$f['sender_name'].'</td><td><b>Message:</b></td></tr>
			<tr><td><b>Subject:</b></td><td>'.$f['subject'].'</td><td rowspan="4" class="message">'.$f['message'].'</td></tr>
			<tr><td><b>Date</b></td><td>'.$f['senddate'].'</td></tr>
			<tr><td></td><td>';

			if($type == 0)
			{
				echo '<a href="?page=messages&new&reply='.$f['id'].'">
					<button>Reply</button>
				</a>';
			}
				
			echo '</td></tr>';


	echo '</table>';
}


?>